package dao

import (
	"context"
	"github.com/ecodeclub/ekit/slice"
	"github.com/olivere/elastic/v7"
	"strconv"
)

type BizTag struct {
	Id    int64
	Uid   int64  `json:"uid"`
	Biz   string `json:"biz"`
	BizId int64  `json:"biz_id"`
	Tags  string `json:"tags"`
}
type TagElasticDAO struct {
	client *elastic.Client
}

func (h *TagElasticDAO) InputTag(ctx context.Context, Tag BizTag) error {
	_, err := h.client.Index().Index(TagIndexName).Id(strconv.FormatInt(Tag.BizId, 10)).
		BodyJson(Tag).Do(ctx)
	return err
}
func (t *TagElasticDAO) SearchTag(ctx context.Context, uid int64, biz string, keywords []string) ([]int64, error) {
	query := elastic.NewBoolQuery().Must(
		elastic.NewTermQuery("uid", uid),
		elastic.NewTermQuery("biz", biz),
		elastic.NewTermsQueryFromStrings("tags", keywords...),
	)
	resp, err := NewSearcher[BizTag](t.client).Query(query).Do(ctx)
	if err != nil {
		return nil, err
	}

	tagIDs := slice.Map(resp, func(idx int, src BizTag) int64 {
		return src.BizId
	})
	return tagIDs, nil
}
